package com.lyy.common;

import com.alibaba.fastjson.JSONObject;
import io.minio.*;
import io.minio.DownloadObjectArgs.Builder;
import io.minio.errors.ErrorResponseException;
import io.minio.messages.Bucket;
import io.minio.messages.DeleteError;
import io.minio.messages.DeleteObject;
import io.minio.messages.Item;
import lombok.SneakyThrows;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

public class MinioUtil {

    private static MinioClient minioClient;
    /**
     * 存储桶名称
     */
    private static String bucketName;

    public static void init(MinioClient client,String name) {
        MinioUtil.minioClient = client;
        MinioUtil.bucketName = name;
    }

    /**
     * 检查存储桶是否存在
     *
     * @param bucketName 存储桶名称
     * @return
     */
    @SneakyThrows
    public static boolean bucketExists(String bucketName) {
        boolean flag = false;
        flag = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        if (flag) {
            return true;
        }
        return false;
    }

    /**
     * 创建存储桶
     */
    @SneakyThrows
    public static boolean makeBucket() {
        boolean flag = bucketExists(bucketName);
        if (!flag) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            return true;
        } else {
            return false;
        }
    }

    /**
     * 列出所有存储桶名称
     *
     * @return
     */
    @SneakyThrows
    public static List<String> listBucketNames() {
        List<Bucket> bucketList = listBuckets();
        List<String> bucketListName = new ArrayList<>();
        for (Bucket bucket : bucketList) {
            bucketListName.add(bucket.name());
        }
        return bucketListName;
    }

    /**
     * 列出所有存储桶
     *
     * @return
     */
    @SneakyThrows
    public static List<Bucket> listBuckets() {
        return minioClient.listBuckets();
    }

    /**
     * 删除存储桶
     *
     * @return
     */
    @SneakyThrows
    public static boolean removeBucket() {
        boolean flag = bucketExists(bucketName);
        if (flag) {
            Iterable<Result<Item>> myObjects = listObjects();
            for (Result<Item> result : myObjects) {
                Item item = result.get();
                // 有对象文件，则删除失败
                if (item.size() > 0) {
                    return false;
                }
            }
            // 删除存储桶，注意，只有存储桶为空时才能删除成功。
            minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build());
            flag = bucketExists(bucketName);
            if (!flag) {
                return true;
            }

        }
        return false;
    }

    /**
     * 列出存储桶中的所有对象名称
     * @return
     */
    @SneakyThrows
    public static List<String> listObjectNames() {
        List<String> listObjectNames = new ArrayList<>();
        boolean flag = bucketExists(bucketName);
        if (flag) {
            Iterable<Result<Item>> myObjects = listObjects();
            for (Result<Item> result : myObjects) {
                Item item = result.get();
                listObjectNames.add(item.objectName());
            }
        }
        return listObjectNames;
    }

    /**
     * 列出存储桶中的所有对象
     * @return
     */
    @SneakyThrows
    public static Iterable<Result<Item>> listObjects() {
        boolean flag = bucketExists(bucketName);
        if (flag) {
            return minioClient.listObjects(ListObjectsArgs.builder().bucket(bucketName).build());
        }
        return null;
    }

    /**
     * 通过文件上传到对象
     * @param objectName 存储桶里的对象名称
     * @param fileName   File name
     * @return
     */
    @SneakyThrows
    public static boolean putObject(String objectName, String fileName) {
        boolean flag = bucketExists(bucketName);
        if (flag) {
            UploadObjectArgs uploadObjectArgs = UploadObjectArgs.builder().bucket(bucketName).object(objectName).filename(fileName).build();
            minioClient.uploadObject(uploadObjectArgs);
        }
        return true;

    }

    /**
     * 文件上传
     * @param multipartFile
     */
    @SneakyThrows
    public static void putObject(MultipartFile multipartFile, String filename) {
        InputStream stream = multipartFile.getInputStream();
        long fileSize = multipartFile.getSize();
        int partSize = PutObjectArgs.MIN_MULTIPART_SIZE;
        String contentType = multipartFile.getContentType();
        io.minio.PutObjectArgs.Builder builder = PutObjectArgs.builder();
        builder.bucket(bucketName);
        builder.object(filename);
        builder.stream(stream,fileSize,partSize);
        builder.contentType(contentType);
        minioClient.putObject(builder.build());
    }

    /**
     * 字符串文件上传
     *
     */
    @SneakyThrows
    public static JSONObject putStringObject(String fileString, String fileName) {
        // 原文件名称
        String trueName = fileName;
        int i = trueName.indexOf(".");
        String ext = fileName.substring(i);
        // 文件后缀名
//        String ext = FilenameUtils.getExtension(trueName);
        fileName = String.valueOf(System.currentTimeMillis() + new Random().nextInt(10000));
        File saveFile = null;
        JSONObject jsonObject = new JSONObject();
        try {
            saveFile = File.createTempFile(fileName,ext);
            ImageBase64.stringToFile(fileString,saveFile.getParent(),saveFile.getName());
            putObject(fileName + ext,new FileInputStream(saveFile));
            jsonObject.put("trueName", trueName);
            jsonObject.put("state", "SUCCESS");
            String url = "/api/download/ossFile?originalName=" + trueName + "&fileName=" + fileName + ext;
            jsonObject.put("url", url);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

    /**
     * 通过InputStream上传对象
     *
     * @param objectName 存储桶里的对象名称
     * @param stream     要上传的流
     * @return
     */
    @SneakyThrows
    public static boolean putObject(String objectName, InputStream stream) {
        boolean flag = bucketExists(bucketName);
        if (flag) {
            long fileSize = stream.available();
            int partSize = PutObjectArgs.MIN_MULTIPART_SIZE;
            io.minio.PutObjectArgs.Builder builder = PutObjectArgs.builder();
            builder.bucket(bucketName);
            builder.object(objectName);
            builder.stream(stream,fileSize,partSize);
            minioClient.putObject(builder.build());
            return true;
        }
        return false;
    }

    /**
     * 以流的形式获取一个文件对象
     * @param objectName 存储桶里的对象名称
     * @return
     */
    @SneakyThrows
    public static InputStream getObject(String objectName) {
        boolean flag = bucketExists(bucketName);
        if (flag) {
            InputStream stream =  minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(objectName).build());
            return stream;
        }
        return null;
    }

    /**
     * 以流的形式获取一个文件对象（断点下载）
     * @param objectName 存储桶里的对象名称
     * @param offset     起始字节的位置
     * @param length     要读取的长度 (可选，如果无值则代表读到文件结尾)
     * @return
     */
    @SneakyThrows
    public static InputStream getObject(String objectName, long offset, Long length) {
        boolean flag = bucketExists(bucketName);
        if (flag) {
            io.minio.GetObjectArgs.Builder builder = GetObjectArgs.builder();
            builder.bucket(bucketName).object(objectName);
            InputStream stream =  minioClient.getObject(builder.build());
            return stream;
        }
        return null;
    }

    /**
     * 下载并将文件保存到本地
     * @param objectName 存储桶里的对象名称
     * @param fileName   File name
     * @return
     */
    @SneakyThrows
    public static boolean getObject(String objectName, String fileName) {
        boolean flag = bucketExists(bucketName);
        if (flag) {
            DownloadObjectArgs.Builder builder = new Builder();
            builder.bucket(bucketName);
            builder.object(objectName);
            builder.filename(fileName);
            minioClient.downloadObject(builder.build());
            return true;
        }
        return false;
    }

    /**
     * 删除一个对象
     * @param objectName 存储桶里的对象名称
     */
    @SneakyThrows
    public static boolean removeObject(String objectName) {
        boolean flag = bucketExists(bucketName);
        if (flag) {
            minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(objectName).build());
            return true;
        }
        return false;
    }

    /**
     * 删除指定桶的多个文件对象,返回删除错误的对象列表，全部删除成功，返回空列表
     * @param objectNames 含有要删除的多个object名称的迭代器对象
     * @return
     */
    @SneakyThrows
    public static List<String> removeObject(List<String> objectNames) {
        List<String> deleteErrorNames = new ArrayList<>();
        boolean flag = bucketExists(bucketName);
        if (flag) {
            Iterable<DeleteObject> objs = objectNames.stream().map(item->new DeleteObject(item)).collect(Collectors.toList());
            RemoveObjectsArgs removeObjectsArgs = RemoveObjectsArgs.builder().bucket(bucketName).objects(objs).build();
            Iterable<Result<DeleteError>> results = minioClient.removeObjects(removeObjectsArgs);
            for (Result<DeleteError> result : results) {
                DeleteError error = result.get();
                deleteErrorNames.add(error.objectName());
            }
        }
        return deleteErrorNames;
    }

    /**
     * 生成一个给HTTP GET请求用的presigned URL。
     * 浏览器/移动端的客户端可以用这个URL进行下载，即使其所在的存储桶是私有的。这个presigned URL可以设置一个失效时间，默认值是7天。
     * @param objectName 存储桶里的对象名称
     * @param expires    失效时间（以秒为单位），默认是7天，不得大于七天
     * @return
     */
    @SneakyThrows
    public static String presignedGetObject(String objectName, Integer expires) {
        boolean flag = bucketExists(bucketName);
        String url = "";
        if (flag) {
            url = minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder().bucket(bucketName).object(objectName).expiry(expires).build());
        }
        return url;
    }


    /**
     * 获取对象的元数据
     * @param objectName 存储桶里的对象名称
     * @return
     */
    @SneakyThrows
    public static StatObjectResponse statObject(String objectName) {
        boolean flag = bucketExists(bucketName);
        if (flag) {
            StatObjectResponse statObject = minioClient.statObject(StatObjectArgs.builder().bucket(bucketName).object(objectName).build());
            return statObject;
        }
        return null;
    }




    public static void downloadFile(String fileName, String originalName, HttpServletResponse response) {
        try {
            InputStream file = minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(fileName).build());
            String filename = new String(fileName.getBytes("ISO8859-1"), StandardCharsets.UTF_8);
            if (!StringUtils.isEmpty(originalName)) {
                fileName = originalName;
            }
            response.setHeader("Content-Disposition", "attachment;filename=" + filename);
            ServletOutputStream servletOutputStream = response.getOutputStream();
            int len;
            byte[] buffer = new byte[1024];
            while ((len = file.read(buffer)) > 0) {
                servletOutputStream.write(buffer, 0, len);
            }
            servletOutputStream.flush();
            file.close();
            servletOutputStream.close();
        } catch (ErrorResponseException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args){
        try {

        }catch(Exception e) {

        }
    }
}
